package com.njtoyo.taxi.admin.service.local_service.merchant.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.mapper.master.entity.local_service.GeoMerchantRegion;
import com.njtoyo.taxi.admin.mapper.master.entity.local_service.GeoMerchantRegionArea;
import com.njtoyo.taxi.admin.mapper.master.mapper.GeoCustomerRegionMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.local_service.GeoMerchantRegionAreaMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.local_service.GeoMerchantRegionMapper;
import com.njtoyo.taxi.admin.rest.presenter.local_service.platform.MerchantCategoryPagePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.platform.MerchantWrapper;
import com.njtoyo.taxi.admin.service.local_service.merchant.MerchantRegionService;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import com.njtoyo.taxi.entity.backend.AdminUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.util.ObjectUtil.isEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;
import static java.util.stream.Collectors.toList;

@Service
@Slf4j
public class MerchantRegionServiceImpl implements MerchantRegionService {

    @Autowired
    private OperationRecordHelper operationRecordHelper;

    @Autowired
    private GeoMerchantRegionMapper merchantRegionMapper;

    @Autowired
    private GeoMerchantRegionAreaMapper merchantRegionAreaMapper;

    @Autowired
    private GeoCustomerRegionMapper customerRegionMapper;


    /**
     * 所有的商户运营区
     *
     * @return
     */
    @Override
    public RestResult<List<GeoMerchantRegion>> all() {

        QueryWrapper<GeoMerchantRegion> wrapper = new QueryWrapper<>();
        List<GeoMerchantRegion> geoMerchantRegions = merchantRegionMapper.selectList(wrapper);

        return RestResult.success(geoMerchantRegions);
    }

    /**
     * 商户运营区列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<MerchantCategoryPagePresenter>> getPage(AdminUser adminUser, MerchantWrapper wrapper) {
        switch (adminUser.getAccountType()) {
            case platform:
                break;
            default:
                return RestResult.failed("账号权限不够");
        }
        Page<MerchantCategoryPagePresenter> page = merchantRegionMapper.getPage(wrapper);
        List<MerchantCategoryPagePresenter> list = page.getRecords();
        if (isNotEmpty(list)) {
            List<Long> ids = page.getRecords().stream().map(MerchantCategoryPagePresenter::getId).collect(toList());

            //包含地区
            List<MerchantCategoryPagePresenter.MerchantCategoryArea> areaList = merchantRegionAreaMapper.regionAreaList(ids);

            list.forEach(results -> {
                Long id = results.getId();
                List<MerchantCategoryPagePresenter.MerchantCategoryArea> areaArrayList =
                        areaList.stream().filter(categoryArea -> categoryArea.getMerchantRegionId().equals(id))
                                .collect(Collectors.toCollection(ArrayList::new));
                results.setArea(areaArrayList);
            });
        }
        return RestResult.success(page);
    }

    /**
     * 商户运营区添加
     *
     * @param wrapper
     * @return
     */
    @Override
    @DSTransactional
    public RestResult add(MerchantWrapper wrapper) {
        //geo_merchant_region
        GeoMerchantRegion geoMerchantRegion = new GeoMerchantRegion();
        geoMerchantRegion.setName(wrapper.getName());
        merchantRegionMapper.insert(geoMerchantRegion);
        Long id = geoMerchantRegion.getId();

        //geo_merchant_region_area
        List<Long> areas = wrapper.getAreas();
        areas.forEach(areaId -> {
            GeoMerchantRegionArea geoMerchantRegionArea = new GeoMerchantRegionArea();
            geoMerchantRegionArea.setMerchantRegionId(id);
            geoMerchantRegionArea.setAreaId(areaId);
            merchantRegionAreaMapper.insert(geoMerchantRegionArea);
        });

        operationRecordHelper.addBusinessLog(String.format("新增了商户运营区 [%d] 的信息", id));
        return RestResult.success();
    }

    /**
     * 商户运营区修改
     *
     * @param id
     * @param wrapper
     * @return
     */
    @Override
    @DSTransactional
    public RestResult update(Long id, MerchantWrapper wrapper) {
        GeoMerchantRegion geoMerchantRegion = merchantRegionMapper.selectById(id);
        if (isEmpty(geoMerchantRegion)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        //名称
        new LambdaUpdateChainWrapper<>(merchantRegionMapper)
                .eq(GeoMerchantRegion::getId, id)
                .set(GeoMerchantRegion::getName, wrapper.getName())
                .set(GeoMerchantRegion::getUpdatedAt, new Date())
                .update();
        QueryWrapper<GeoMerchantRegionArea> merchantRegionQueryWrapper = new QueryWrapper<>();
        merchantRegionQueryWrapper.eq("merchant_region_id", id);
        merchantRegionAreaMapper.delete(merchantRegionQueryWrapper);

        //地区
        List<Long> areas = wrapper.getAreas();
        areas.forEach(areaId -> {
            GeoMerchantRegionArea geoMerchantRegionArea = new GeoMerchantRegionArea();
            geoMerchantRegionArea.setMerchantRegionId(id);
            geoMerchantRegionArea.setAreaId(areaId);
            merchantRegionAreaMapper.insert(geoMerchantRegionArea);
        });
        operationRecordHelper.addBusinessLog(String.format("修改了商户运营区 [%d] 的信息", id));
        return RestResult.success();
    }

    /**
     * 商户运营区删除
     *
     * @param id
     * @return
     */
    @Override
    @DSTransactional
    public RestResult delete(Long id) {
        GeoMerchantRegion geoMerchantRegion = merchantRegionMapper.selectById(id);
        if (isEmpty(geoMerchantRegion)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        QueryWrapper<GeoMerchantRegion> regionQueryWrapper = new QueryWrapper<>();
        regionQueryWrapper.eq("id", id);
        merchantRegionMapper.delete(regionQueryWrapper);

        QueryWrapper<GeoMerchantRegionArea> merchantRegionQueryWrapper = new QueryWrapper<>();
        merchantRegionQueryWrapper.eq("merchant_region_id", id);
        merchantRegionAreaMapper.delete(merchantRegionQueryWrapper);

        operationRecordHelper.addBusinessLog(String.format("删除了商户运营区 [%d] 的信息", id));
        return RestResult.success();
    }

}
